/**
 * @name ProjectEdit
 * @author darcrand
 * @desc 项目新增/更新
 */

import React, { Component } from 'react'
import { Form, Input, Button, Breadcrumb, Select, Modal } from 'antd'
import { inject, observer } from 'mobx-react'
import { ColorPicker, TopBar, FormWrapper } from '@/components'
import { apiGetProjectById, apiAddProject, apiUpdateProject, apiRemoveProject } from '@/apis/project'
import { apiGetUsers } from '@/apis/user'
import styles from './styles.module.less'

// 新增模式使用的路由id
export const CREATE_MODE_ID = 'add'

@inject('user')
@observer
class ProjectEdit extends Component {
  state = {
    isCreateMode: this.props?.match?.params?.id === CREATE_MODE_ID,
    id: this.props?.match?.params?.id,

    userOptions: [],
  }

  refForm = React.createRef()

  componentDidMount() {
    this.init()
  }

  init = async () => {
    const { isCreateMode, id } = this.state
    const currUserId = this.props.user?.info?._id

    try {
      const { list } = await apiGetUsers()
      // 转化数据,当前用户必须在成员中
      this.setState({
        userOptions: list.map(v => ({ value: v._id, label: v.nickname, disabled: v._id === currUserId })),
      })
    } catch (err) {}

    if (isCreateMode) {
      // 随机设置颜色
      const bgColor = ColorPicker.COLORS[Math.floor(Math.random() * ColorPicker.COLORS.length)]
      this.refForm.current.setFieldsValue({ title: '', desc: '', bgColor, members: [currUserId] })
    } else {
      try {
        const data = await apiGetProjectById(id)
        this.refForm.current.setFieldsValue({ ...data, members: data.members.map(u => u._id) })
      } catch (err) {}
    }
  }

  onFinish = async (values = {}) => {
    const { isCreateMode, id } = this.state
    try {
      if (isCreateMode) {
        const pid = await apiAddProject(values)
        this.props.history.replace(`/project/${pid}`)
      } else {
        await apiUpdateProject(id, values)
        this.props.history.replace(`/project/${id}`)
      }
    } catch (err) {}
  }

  beforeRemove = () => {
    Modal.confirm({
      title: 'Warning',
      content: 'This project and all todos in this will be delete. Are you sure you want to delete it? ',
      okText: 'Delete',
      onOk: this.removeProject,
    })
  }

  removeProject = async () => {
    const { id } = this.state
    try {
      await apiRemoveProject(id)
      this.props.history.replace('/')
    } catch (err) {}
  }

  render() {
    const { isCreateMode, userOptions } = this.state
    return (
      <>
        <TopBar />
        <div className={styles.container}>
          <Breadcrumb className={styles.top_links}>
            <Breadcrumb.Item href='/'>Home</Breadcrumb.Item>
            <Breadcrumb.Item>Project {isCreateMode ? 'Create' : 'Edit'}</Breadcrumb.Item>
          </Breadcrumb>

          <FormWrapper>
            <Form ref={this.refForm} {...FormWrapper.FORM_ITEM_LAYOUT} onFinish={this.onFinish}>
              <Form.Item name='title' label='Title' rules={[{ required: true, message: 'Please input a title!' }]}>
                <Input />
              </Form.Item>
              <Form.Item name='desc' label='Description'>
                <Input.TextArea rows={5} />
              </Form.Item>
              <Form.Item name='members' label='Members'>
                <Select mode='multiple' options={userOptions}></Select>
              </Form.Item>
              <Form.Item name='bgColor' label='Color'>
                <ColorPicker style={{ margin: 0 }} />
              </Form.Item>

              <Form.Item {...FormWrapper.TAIL_FORM_LAYOUT}>
                <Button htmlType='submit' type='primary'>
                  Save
                </Button>
                {!isCreateMode && (
                  <Button style={{ marginLeft: 10 }} onClick={this.beforeRemove}>
                    Delete
                  </Button>
                )}
              </Form.Item>
            </Form>
          </FormWrapper>
        </div>
      </>
    )
  }
}

export default ProjectEdit
